package com.citywy.controller;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Controller
@RequestMapping("/upload")
public class UploadController {
    /**
     * 文件上传回顾
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("up1")
    public String upload1(HttpServletRequest request) throws Exception{
        //获取要上传的文件目录
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        //创建File对象，一会向该路径下上传文件
        File file = new File(path);
        //判断路径是否存在，如果不存在，创建该路径
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建磁盘文件项工厂
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //解析request对象
        List<FileItem> list = fileUpload.parseRequest(request);
        //遍历
        for(FileItem fileItem:list){
            //判断文件项是普通字段,还是上传的文件
            if(fileItem.isFormField()){

            }else{
                //上传文件项
                //获取上传文件名称
                String fileName = fileItem.getName();
                //上传文件
                fileItem.write(new File(file,fileName));
                //删除临时文件
                fileItem.delete();
            }

        }
        return "/WEB-INF/pages/success";
    }

    /**
     * SpringMVC方式文件上传
     * @param request
     * @param upload
     * @return
     * @throws Exception
     */
    @RequestMapping("up2")
    public String upload2(HttpServletRequest request, MultipartFile upload) throws Exception{
        System.out.println("springmvc方式文件上传....");
        //获取到要上传的文件目录
        String path = request.getSession().getServletContext().getRealPath("/uploads");
        //创建File对象，一会向该路径下上传文件
        File file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        //获取上传文件的名称
        String fileName = upload.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replaceAll("-","").toUpperCase();
        //把文件名称唯一化
        fileName = uuid+"_"+fileName;
        //上传文件
        upload.transferTo(new File(file,fileName));
        return "/WEB-INF/pages/success";
    }
}
